import util from '../../../utils/utils';
import Dialog from "../../../dist/dialog/dialog";

import {
  walktohomeHttp
} from '../../../api/walktohome';
import {
  HomeHttp
} from '../../../api/home.js'
import {
  UserHttp
} from '../../../api/user.js'
const walktoModel = new walktohomeHttp();
const userHttp = new UserHttp()
const homeModel = new HomeHttp()
let redpackAd = '';
Page({
  /**
   * 页面的初始数据
   */
  initStatus: false,
  updateAddressOrderId: 0,
  data: {
    initUser: true,
    downTime: 0, //倒计时
    downTimeData: {},
    helpInfo: {},
    isShowShareBtn: false,
    isShowErrorPopup: false,
    errorPopupInfo: {},
    recommendList: [], //推荐商品
    orderNumber: 0, //订单号
    orderInfo: {}, //订单详情1
    goodsInfo: {}, //商品详情
    isBtnClick: false, //是否可以点击按钮
    btnTexe: '免单已结束', //按钮文字
    page: 1,
    adId: "adunit-b5fbbe96f27d0e64",
    userInfo: {},
    freeInfo: {
      free_order_total_price: 0
    },
    shareImg: '',
  },
  initPage: function(options) {
    console.log(options.hasOwnProperty('id'))
    if (options.hasOwnProperty('id')) {
      this.setData({
        orderNumber: options.id
      })
      this.initData()
    } else {
      util.msg("订单号错误")
    }
    this.initAd()
  },
  //初始化数据
  initData() {
    let self = this
    this.getUserInfo(function(userInfo) {
      self.setData({
        userInfo: userInfo
      });
      wx.showNavigationBarLoading();
      self.httpGetOrderDetailr()
      self.httpGetFreesheetInfo()
      self.httpGetGoodsRecommend(false)
      self.httpFreesheetImg()
      self.initAd()
    }, function() {
      self.setData({
        initUser: false
      })
    })
  },
  lookAd() {
    redpackAd.show().catch(err => {
      redpackAd.load().then(() => redpackAd.show())
    })
  },
  initAd() {
    console.log('initad')
    if (wx.createRewardedVideoAd) {
      let self = this
      let {
        adId
      } = self.data
      console.log(adId)
      redpackAd = wx.createRewardedVideoAd({
        adUnitId: adId
      })
      redpackAd.onLoad()
      redpackAd.onError((err) => {
        console.log('onError event emit');
        util.msg("视频加载错误,重新加载页面试试吧");
        if (err.errCode) {
          console.log('广告组件失败响应码：' + err.errCode);
        }
      })
      redpackAd.onClose((res) => {
        if (res && res.isEnded || res === undefined) {
          console.log('正常播放结束，下放奖励');
          self.setData({
            isShowErrorPopup: false
          })
          self.httpLookViewADPeaDouble()
        } else {
          util.msg("您的视频还没看完，无法获得奖励！");
        }
      })
    }
  },
  httpLookViewADPeaDouble() {
    walktoModel.getPeaDouble({
      ad_id: this.data.adId,
      complete: 1,
      need_type: 1,
      pea_id: this.data.helpInfo.pea_id
    }).then((res) => {
      util.msg("翻倍成功")
      console.log(res)
    })

  },
  //自定义倒计时
  onDownTimeChange(e) {
    this.setData({
      downTimeData: e.detail
    });
  },
  //下拉
  onPullDownRefresh() {
    this.initData()
  },

  // 获取订单信息
  httpGetOrderDetailr() {
    return userHttp.getOrderDetailr({
      orderNumber: this.data.orderNumber
    }).then((res) => {
      this.setData({
        goodsInfo: this.maxPriceGoods(res.goodsInfo),
        orderInfo: res
      })
      console.log(res)
      wx.hideNavigationBarLoading();
      wx.stopPullDownRefresh();
    }).catch(err => {
      util.msg("网络错误,请检查后重试!")
      wx.hideNavigationBarLoading();
      wx.stopPullDownRefresh();
    })
  },
  //价格最高的商品
  maxPriceGoods(res) {
    let i = 0;
    let goods = res[0]
    let goodsNum = 0
    for (i; i < res.length; i++) {
      //计算数量
      goodsNum = goodsNum + res[i]['goodsNum']
      //判断最高价格
      if (res[i]['realPrice'] > goods['realPrice']) {
        goods = res[i]
      }
    }
    goods['goodsNum'] = goodsNum
    return goods
  },






  //点击按钮
  onBtnClick() {
    if (this.data.isBtnClick) {
      this.httpHelpFreesheet()
      this.setData({
        isBtnClick: false
      })
    }
  },
  //帮他面免单
  httpHelpFreesheet() {
    let self = this
    homeModel.helpFreesheet({
      ordernum: this.data.orderNumber
    }).then((res) => {
      this.setData({
        errorPopupInfo: {
          img: '/images/me/icon_dou.png',
          btnText: "幸运豆翻倍x2",
          myDou: self.userInfo.common.pea_blance
        },
        isShowErrorPopup: true,
        helpInfo: res
      })
      console.log(res)
      this.httpGetFreesheetInfo()
    })
  },

  //获取页面数据
  httpGetFreesheetInfo() {
    homeModel.getFreesheetInfo({
      ordernum: this.data.orderNumber
    }).then((res) => {
      let now = new Date().getTime()
      let time = res.expire_time * 1000 - now
      if (time <= 0) {
        this.setData({
          isBtnClick: false,
          btnTexe: "免单已结束",
        })
      } else {
        if (res.isOthers === 1) {
          if (res.status == 2) {
            this.setData({
              isBtnClick: true,
              btnTexe: "帮TA免单",
            })
          }
          if (res.status == 1) {
            this.setData({
              isBtnClick: false,
              btnTexe: "已参与"
            })
          }
          this.setData({
            isShowShareBtn: false
          })
        } else {
          this.setData({
            isShowShareBtn: true
          })
        }
      }
      this.setData({
        downTime: time,
        freeInfo: res
      })
    })

  },
  //自定义分享
  onShareAppMessage: function(res) {
    let name = this.data.userInfo.nickname
    if (res.from == "button") {
      return {
        title: name + '@您，我在巷友申请免单，快来帮帮我！',
        path: '/pages/order/freeSheet/index?id=' + this.data.orderNumber,
        imageUrl: this.data.shareImg
      }
    } else {
      return {
        title: '我在巷友申请免单，快来帮帮我！',
        path: '/pages/order/freeSheet/index?id=' + this.data.orderNumber,
        imageUrl: this.data.shareImg
      }
    }
  },

  // 获取推荐商品列表
  httpGetGoodsRecommend(isLoading) {
    let page = this.data.recommendPage;
    return homeModel.getGoodsRecommend({
      "client_type": 3,
      "page": page,
      "page_size": 20,
    }, isLoading).then((res) => {
      res = this.getGoodsList(res.recommend_list)
      this.setData({
        recommendList: page === 1 ? res : this.data.recommendList.concat(res)
      })
    })
  },
  // 获取商品列表
  getGoodsList(res) {
    let i = 0;
    let goodslist = [];
    for (i; i < res.length; i++) {
      res[i]['goods']['price'] = res[i]['goods']['lowestPrice']
      goodslist.push(res[i].goods)
    }
    return goodslist
  },
  //获取分享图片
  httpFreesheetImg() {
    homeModel.FreesheetImg({
      ordernum: this.data.orderNumber
    }).then((res) => {
      this.setData({
        shareImg: res
      })
      console.log(res)
    })
  }
});
